import 'package:auto_route/auto_route.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/core/network/api_client_provider.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/lifeCircle/data/repository/life_repository_impl.dart';
import 'package:casdon/modules/lifeCircle/domain/usecase/life_topic_list_usecase.dart';
import 'package:casdon/modules/lifeCircle/providers/life_provider.dart';
import 'package:casdon/modules/lifeCircle/services/follow_status_sync_service.dart';
import 'package:casdon/modules/lifeCircle/ui/widgets/topic_item_widget.dart';
import 'package:casdon/modules/lifeCircle/data/model/life_topic_module.dart';
import 'package:casdon/modules/me/data/repository/me_repository_impl.dart';
import 'package:casdon/auto_router.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 生活圈用户话题列表，主要用在首页的各个tabview中
class LifeTopicListScreen extends ConsumerStatefulWidget {
  final String subjectId;
  final ScrollController? controller;
  final bool? isFollowTab; // 是否为“关注”页（用于空态按钮显示）
  final VoidCallback? onGoExplore; // 点击“去逛逛”回调（切到“推荐”）

  const LifeTopicListScreen({
    super.key,
    required this.subjectId,
    required this.controller,
    this.isFollowTab,
    this.onGoExplore,
  });

  @override
  ConsumerState<LifeTopicListScreen> createState() => _LifeTopicListState();
}

class _LifeTopicListState extends ConsumerState<LifeTopicListScreen> {
  bool _hasInitialized = false;
  bool _isLoadMorePending = false;

  @override
  void initState() {
    super.initState();
    // 延迟初始化，避免重复加载
    Future.microtask(() {
      if (mounted && !_hasInitialized) {
        final currentState = ref.read(
          lifeTopicListNotifierProvider(widget.subjectId),
        );
        final notifier = ref.read(
          lifeTopicListNotifierProvider(widget.subjectId).notifier,
        );

        // 只在数据未加载或出错时才刷新
        if (currentState.isLoading) {
          // 正在加载中，不重复刷新，标记为已初始化
          _hasInitialized = true;
        } else if (currentState.hasValue &&
            currentState.value?.data != null &&
            currentState.value!.data!.isNotEmpty) {
          // 已有数据，不刷新
          _hasInitialized = true;
        } else {
          // 数据为空或出错，需要刷新
          notifier.refresh();
          _hasInitialized = true;
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(lifeTopicListNotifierProvider(widget.subjectId));

    return Container(
      color: Theme.of(context).colorScheme.surface,
      child: state.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (error, stackTrace) => Center(child: Text("")),
        data: (data) {
          final items = data.data ?? [];
          if (items.isEmpty) {
            final isFollow =
                widget.isFollowTab ??
                (widget.subjectId == LifeTopicListUsecase.followSubjectId);
            return _buildEmpty(context, isFollow: isFollow);
          }
          // 每个 tab 使用唯一的 key，确保 ExtendedNestedScrollView 能正确管理滚动
          return NotificationListener<ScrollNotification>(
            onNotification: _handleScrollNotification,
            child: ListView.builder(
              key: PageStorageKey('life_topic_list_${widget.subjectId}'),
              // 让 ExtendedNestedScrollView 管理滚动，滚动会同步到外层
              padding: EdgeInsets.symmetric(vertical: 8.h),
              physics: const ClampingScrollPhysics(),
              cacheExtent: 1000,
              addAutomaticKeepAlives: true,
              addRepaintBoundaries: true,
              // 如果有加载更多状态或没有更多数据，在底部显示指示器
              itemCount:
                  items.length + (data.isLoadingMore || !data.hasMore ? 1 : 0),
              itemBuilder: (_, i) {
                // 如果是最后一个 item
                if (i == items.length) {
                  // 正在加载更多，显示加载指示器
                  if (data.isLoadingMore) {
                    return Container(
                      padding: EdgeInsets.symmetric(vertical: 16.h),
                      alignment: Alignment.center,
                      child: const CircularProgressIndicator(),
                    );
                  }
                  // 没有更多数据，显示提示
                  if (!data.hasMore) {
                    return Container(
                      padding: EdgeInsets.symmetric(vertical: 16.h),
                      alignment: Alignment.center,
                      child: Text(
                        '没有更多了',
                        style: TextStyle(
                          color: Colors.grey.shade500,
                          fontSize: 12.r,
                        ),
                      ),
                    );
                  }
                }

                final item = items[i];
                return TopicItemWidget(
                  key: ValueKey('topic_item_${item.id}'),
                  topic: item,
                  showFollowBtn:
                      item.isFollow == false && item.isMyTopic == false,
                  onCommentTap: () => _handleCommentTap(context, item.id),
                  onZanTap: (topic) => _handleZanTap(context, topic),
                  onAvaterTap: () => _handleAvaterTap(
                    context,
                    item.userId,
                    item.userNickname,
                    item.avatar,
                  ),
                  onFollowTap: () => _handleFollowTap(context, item),
                  onContentTap: () => _handleCommentTap(context, item.id),
                );
              },
            ),
          );
        },
      ),
    );
  }

  // 不再需要 dispose，因为没有需要释放的资源

  bool _handleScrollNotification(ScrollNotification notification) {
    if (notification.metrics.maxScrollExtent <= 0) {
      return false;
    }

    if (notification is ScrollUpdateNotification ||
        notification is OverscrollNotification) {
      final threshold = (notification.metrics.maxScrollExtent - 120).clamp(
        0,
        double.infinity,
      );
      if (notification.metrics.pixels >= threshold) {
        _triggerLoadMoreIfNeeded();
      }
    }
    return false;
  }

  void _triggerLoadMoreIfNeeded() {
    if (_isLoadMorePending) return;
    final asyncState = ref.read(
      lifeTopicListNotifierProvider(widget.subjectId),
    );
    final listState = asyncState.valueOrNull;
    if (listState == null || listState.isLoadingMore || !listState.hasMore) {
      return;
    }
    _isLoadMorePending = true;
    ref
        .read(lifeTopicListNotifierProvider(widget.subjectId).notifier)
        .loadMore()
        .whenComplete(() {
          _isLoadMorePending = false;
        });
  }

  Widget _buildEmpty(BuildContext context, {required bool isFollow}) {
    return Center(
      child: Padding(
        padding: EdgeInsets.only(top: 0.h),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Image.asset(
              Assets.images.emptyData.path,
              width: 120.w,
              height: 80.h,
            ),
            SizedBox(height: 12.h),
            Text(
              isFollow ? '暂无关注的人' : '暂无内容',
              style: TextStyle(color: Colors.grey.shade500),
            ),
            if (isFollow) ...[
              SizedBox(height: 12.h),
              PrimaryButton(
                text: '去逛逛',
                width: 95.w,
                height: 32.h,
                onPressed: widget.onGoExplore,
              ),
            ],
          ],
        ),
      ),
    );
  }

  void _handleCommentTap(BuildContext context, String topicId) {
    context.router.push(LifeTopicDetailRoute(topicId: topicId));
  }

  Future<void> _handleZanTap(
    BuildContext context,
    LifeTopicModule topic,
  ) async {
    try {
      final repository = LifeRepositoryImpl(
        apiClient: ref.read(apiClientProvider),
      );

      final isLiked = topic.isLike;
      final currentLikes = topic.likes;

      // 调用点赞接口
      await repository.likeTopic(
        id: topic.id,
        type: 0, // 0-帖子，1-评论
        flag: isLiked ? 0 : 1, // 0-取消点赞，1-点赞
      );

      // 更新本地状态，避免刷新整个列表
      final newLikesCount = isLiked ? currentLikes - 1 : currentLikes + 1;
      ref
          .read(lifeTopicListNotifierProvider(widget.subjectId).notifier)
          .updateTopicLikeStatus(topic.id, !isLiked, newLikesCount);
    } on DioException catch (e) {
    } catch (e) {
      // 处理错误，可以显示 Toast
      debugPrint("点赞操作失败: $e");
    }
  }

  void _handleAvaterTap(
    BuildContext context,
    String userId,
    String userNickName,
    String avatar,
  ) async {
    final storage = ref.read(authStorageProvider.notifier);
    final uid = await storage.getUserId();
    if (context.mounted == false) return;
    if (uid == userId) {
      context.router.push(const LifeSelfHomeRoute());
      return;
    }
    context.router.push(
      LifeUserHomeRoute(userId: userId, nickName: userNickName, avatar: avatar),
    );
  }

  Future<void> _handleFollowTap(
    BuildContext context,
    LifeTopicModule topic,
  ) async {
    try {
      final repository = MeRepositoryImpl(
        apiClient: ref.read(apiClientProvider),
      );
      final isFollowed = topic.isFollow;
      final newFollowStatus = !isFollowed;

      // 取消关注前弹确认
      if (isFollowed) {
        final confirm = await showCustomConfirmDialog(
          context: context,
          title: '',
          content: '不再关注该作者？',
          confirmText: '不再关注',
          cancelText: '取消',
        );
        if (confirm != true) return;
      }

      await repository.followUser(
        followUuid: topic.userId,
        flag: isFollowed ? "0" : "1", // "1"：关注，"0"：取消关注
      );

      if (isFollowed == false) {
        ToastUtil.show("关注成功");
      } else {
        ToastUtil.show("取消关注成功");
      }

      // 使用统一的同步服务更新所有相关列表的状态
      final syncService = FollowStatusSyncService(ref);
      syncService.syncFollowStatus(topic.userId, newFollowStatus);
    } on DioException catch (e) {
    } catch (e) {
      // 处理错误，可以显示 Toast
      debugPrint("关注操作失败: $e");
    }
  }
}
